import logging
import json
import random
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.action_chains import ActionChains
from urllib.parse import urlparse

captureds_urls = []


def random_sleep_time():
    # 等待 1 到 5 秒的随机时间，精确到毫秒
    sleep_time = random.uniform(5, 10)
    logging.info(f"等待 {sleep_time:.3f} 秒...")
    time.sleep(sleep_time)


def view_geek_info(driver, dynamic_id):
    try:
        wait = WebDriverWait(driver, 10)  # 等待最多10秒
        container = wait.until(EC.presence_of_element_located((By.XPATH,
                                                               '//*[@id="container"]/div[1]/div/div[2]/div[2]/div[1]/div[2]/div')))
        random_sleep_time()

        # 清空浏览器日志缓冲区
        driver.get_log("performance")

        # 通过动态ID查找目标元素
        target_element = container.find_element(By.XPATH, f'//*[@id="{dynamic_id}"]')

        # 创建 ActionChains 对象
        actions = ActionChains(driver)

        # 执行鼠标移动到目标元素并点击
        actions.move_to_element(target_element).perform()
        random_sleep_time()  # 等待一段时间模拟鼠标移动的动作

        # 执行点击操作
        actions.click().perform()

        # 等待一段时间
        random_sleep_time()

        # 点击查看简历详情按钮
        refresh_btn = driver.find_element(By.XPATH,
                                          '//*[@id="container"]/div[1]/div/div[2]/div[2]/div[2]/div[1]/div[1]/div[1]/div/div[2]/div[1]/div')
        refresh_btn.click()

        # 等待页面加载
        random_sleep_time()
        logging.info("简历详情页面")

        # 每次页面加载后，启用 Network 并设置缓冲区
        driver.execute_cdp_cmd("Network.enable", {
            "maxTotalBufferSize": 10000000,
            "maxResourceBufferSize": 5000000
        })

        # 等待一段时间，确保页面加载并发起请求
        random_sleep_time()

        # 获取浏览器的性能日志
        logs = driver.get_log("performance")

        # 等待弹框关闭按钮的出现
        close_button = WebDriverWait(driver, 3).until(
            EC.presence_of_element_located((By.CLASS_NAME, 'boss-popup__close'))
        )
        random_sleep_time()

        # 关闭窗口
        close_button.click()
        logging.info("已关闭弹框。")
        random_sleep_time()

        # 遍历日志，捕获相关网络请求和响应
        for item in logs:
            log = json.loads(item["message"])["message"]

            if log["method"] == 'Network.responseReceived':
                # 获取响应的URL
                urls = log['params']['response']['url']
                captureds_urls.append(urls)

                # 定义目标 URL 的路径部分
                target_urls_pattern = "https://www.zhipin.com/wapi/zpjob/view/geek/info"

                try:
                    # 逐个处理 captureds_urls 中的每个 URL
                    for captured_url in captureds_urls:
                        # 解析 URL
                        parsed_urls = urlparse(captured_url)
                        urls_path = f"{parsed_urls.scheme}://{parsed_urls.netloc}{parsed_urls.path}"

                        # 检查 URL 路径是否匹配目标 URL
                        if urls_path == target_urls_pattern:
                            # print("是目标 URL 响应")
                            break
                except Exception as e:
                    print(f"发生错误: {e}")

                # 使用检查 URL 是否包含目标路径部分
                if target_urls_pattern not in urls:
                    continue  # 如果匹配目标 URL，继续处理（或执行其他逻辑）

                # 打印请求的 URL
                print('请求 URL:', urls)
                # 获取请求的ID
                request_id = log['params']['requestId']

                # 尝试获取请求的POST数据
                try:
                    request_data = driver.execute_cdp_cmd('Network.getRequestPostData',
                                                          {'requestId': request_id})
                    print('请求数据:', request_data)
                except WebDriverException:  # 没有后台数据获取时会有异常
                    request_data = None

                # 获取响应的主体内容
                try:
                    response_body = driver.execute_cdp_cmd('Network.getResponseBody',
                                                           {'requestId': request_id}).get(
                        'body', None)
                    print('响应体:', response_body)
                except WebDriverException as e:
                    print(f"获取响应失败: {e}")

                # 解析 JSON 数据
                data = json.loads(response_body)  # 将响应体解析为字典
                # 获取字段
                geek_detail_info = data.get('zpData', {}).get('geekDetailInfo', {})
                geek_base_info = geek_detail_info.get('geekBaseInfo', {})

                # 获取 字段值
                large = geek_base_info.get('large')  # 头像
                age = geek_base_info.get('age')
                gender = geek_base_info.get('gender')  # 性别，0女，1男（1）
                activeTimeDesc = geek_base_info.get('activeTimeDesc')  # 活跃时间
                degree = geek_base_info.get('degree')
                degreeCategory = geek_base_info.get('degreeCategory')  # 毕业学校
                email = geek_base_info.get('email')  # 邮箱
                workYears = geek_base_info.get('workYears')  # 工作年限
                applyStatusContent = geek_base_info.get('applyStatusContent')  # 求职状态（在职-离职）（1)
                encryptGeekId = geek_base_info.get('encryptGeekId')
                student = geek_base_info.get('student')
                userDescription = geek_base_info.get('userDescription')  # 个人介绍
                studyAbroadCert = geek_base_info.get('studyAbroadCert')
                locationName = geek_base_info.get('locationName')  # 工作地址
                access_token = "8486cf56-e9a6-4ea6-b877-af3334629159"
                name = geek_base_info.get('name')  # 姓名（1）
                ageDesc = geek_base_info.get('ageDesc')  # 年龄（1）
                positionName = geek_base_info.get('positionName')  # 期望职位（岗位）（1）

                # 获取 geekEduExpList 和 geekWorkExpList
                geek_Certification_List = geek_detail_info.get('geekCertificationList', [])  # 技能
                geek_edu_exp_list = geek_detail_info.get('geekEduExpList', [])  # 专业
                geek_work_exp_list = geek_detail_info.get('geekWorkExpList', [])  # 工作经验
                geek_ExpPos_List = geek_detail_info.get('geekExpPosList', [])  # 期望薪资与职位
                geek_WorkExp_List = geek_detail_info.get('geekWorkExpList', [])  # 工作经验

                # 打印输出
                print(f"Large: {large}")
                print(f"Degree: {gender}")
                print(f"age: {age}")
                print(f"Active Time Desc: {activeTimeDesc}")
                print(f"Degree: {degree}")
                print(f"Degree Category: {degreeCategory}")
                print(f"Email: {email}")
                print(f"Work Years: {workYears}")
                print(f"Active Time Desc: {activeTimeDesc}")
                print(f"Apply Status Content: {applyStatusContent}")
                print(f"Gender: {encryptGeekId}")
                print(f"Active Time Desc: {student}")
                print(f"Degree: {userDescription}")
                print(f"Degree: {studyAbroadCert}")
                print(f"Degree: {locationName}")
                print(f"Degree: {access_token}")
                print(f"Degree: {name}")
                print(f"Degree: {ageDesc}")
                print(f"Degree: {positionName}")

                print("Education Experience:")
                for edu in geek_edu_exp_list:
                    print(f"- {edu.get('school')} ({edu.get('degreeName')}) - Major: {edu.get('major')}")

                print("Work Experience:")
                for work in geek_work_exp_list:
                    print(
                        f"- Company: {work.get('company')} - Position: {work.get('positionName')} - Period: {work.get('startDate')} to {work.get('endDate')}")

                print("Certifications:")
                for cert in geek_Certification_List:
                    print(f"- {cert.get('certName')} - {cert.get('certOrg')} - {cert.get('certDate')}")

                print("Experience Positions:")
                for exp in geek_ExpPos_List:
                    print(
                        f"- {exp.get('company')} - Position: {exp.get('positionName')} - Period: {exp.get('startDate')} to {exp.get('endDate')}")

                print("Experience Work:")
                for exp in geek_WorkExp_List:
                    print(
                        f"- {exp.get('company')} - Position: {exp.get('positionName')} - Period: {exp.get('startDate')} to {exp.get('endDate')}")
                # 将数据保存为 JSON 格式
                with open('data/view_geek.json', 'a', encoding='utf-8') as f:
                    json.dump(data, f, ensure_ascii=False, indent=4)
                    f.write('\n')  # 为了每条数据写入一行，便于查看
                # # 将获取到的字段值保存 txt
                # with open('data/view_geek.txt', 'a') as f:
                #     f.write(f"姓名：{name}\n")
                #     f.write(f"性别：{gender}\n")
                #     f.write(f"求职状态（在职-离职）：{applyStatusContent}\n")
                #     f.write(f"年龄：{ageDesc}\n")
                #     f.write(f"期望职位（岗位）：{positionName}\n")

    except Exception as e:
        print(f"发生错误: {e}")
